/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.analysis.cli.actions;

import cz.mzk.oai.metadataRepository.analysis.Analysis;
import cz.mzk.oai.metadataRepository.analysis.Analyzer;
import cz.mzk.oai.metadataRepository.analysis.RecordPrintOptions;
import cz.mzk.oai.metadataRepository.analysis.impl.MarcDatafieldAnalysis;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.Repository;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public final class AnalyzeMarcAction extends AnalyzeElementAction {

    private static enum FieldType {

        datafield, controlfield;

        static FieldType parse(String string) throws Exception {
            for (FieldType value : values()) {
                if (value.toString().equals(string)) {
                    return value;
                }
            }
            throw new Exception("No such field type");
        }
    }
    private FieldType FieldType;
    private int datafield;
    private char subfield;

    public AnalyzeMarcAction(Repository repository, String analysisType, String collection, boolean printValues, boolean printIdentifiers, RecordPrintOptions options) throws Exception {
        super(repository, collection, printValues, printIdentifiers, options);
        parseAnalysisType(analysisType);
    }

    private void parseAnalysisType(String analysisTypeStr) throws Exception {
        String[] tokens = analysisTypeStr.split("_");
        if (tokens.length != 3) {
            throw new Exception("illegal syntax '" + analysisTypeStr + "' for " + AnalyzeMarcAction.class.getName());
        }
        FieldType fieldType = FieldType.parse(tokens[0]);
        switch (fieldType) {
            case datafield:
                parseDatafieldAndSubfield(tokens[1], tokens[2]);
                break;
            default:
                throw new Exception("analysis of " + fieldType + " not currently supported ");
        }
    }

    private void parseDatafieldAndSubfield(String datafieldNumber, String subfieldCode) throws Exception {
        try {
            datafield = Integer.parseInt(datafieldNumber);
            if (subfieldCode.length() != 1) {
                throw new Exception("illegal length of subfield code");
            } else {
                subfield = subfieldCode.charAt(0);
            }
        } catch (Throwable e) {
            throw new Exception(e.getMessage());
        }

    }

    @Override
    void analyze(MetadataCollection collection) {
        Analysis analysis = new MarcDatafieldAnalysis(datafield, subfield);
        Analyzer analyzer = new Analyzer(analysis, collection, options);
        analyzer.analyzeAndPrintResults(printValues, printIdentifiers);
    }
}
